package com.example.quartzdemo.context;

import com.example.quartzdemo.dto.TaskDTO;
import com.example.quartzdemo.mapper.TaskMapper;
import lombok.extern.log4j.Log4j2;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 任务容器
 */
@Component
@DependsOn(value = {"quartzManager"})
@Log4j2
public class TaskContext {
 
    @Autowired
    private QuartzManager quartzManager;
 
    @Autowired
    private TaskMapper taskMapper;

    /**
     * 更新任务
     * 刷新频率：10秒
     */
    @Scheduled(fixedRate = 10000)
    public void update() {
        try {
            // 查出所有任务
            List<TaskDTO> taskDTOS = taskMapper.getAllTask();
            // 遍历操作
            for (TaskDTO taskDto : taskDTOS) {
                this.quartzManager.startJobTask(taskDto.getTaskName(), TaskConst.GroupEnum.SYSTEM.name(), taskDto.getCron());
            }
        } catch (SchedulerException e) {
            log.error("初始化定时任务异常", e);
        }
    }
}
